﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;

namespace StockFinder.Services.Brokers
{
    public class EODDATABroker
    {
        public CookieContainer CookieContainer { get; set; }
        public bool LoggedIn { get; set; }

        public void Login()
        {
            CookieContainer cookieContainer = new CookieContainer();

            //1 access main site            
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.eoddata.com/");
            httpWebRequest.CookieContainer = cookieContainer;
            httpWebRequest.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, #/#";
            httpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
            httpWebRequest.Method = "GET";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            var webResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            //2 reference the requested post variables for login e.g. viewstate
            string pageSource = null;

            //get the response details
            using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
            {
                //get the page response
                //pageSource = HttpUtility.HtmlEncode(streamReader.ReadToEnd());
                pageSource = (streamReader.ReadToEnd());
            }            

            //make sure we have a response
            if (string.IsNullOrEmpty(pageSource))
            {
                throw new Exception("Returned null page source from http://www.eoddata.com/");
            }

            //get server variables required for POST
            string viewStateServerVariable = GetSeverSideVariableByToken(pageSource, "VIEWSTATE");
            string previousPageServerVariable = GetSeverSideVariableByToken(pageSource, "PREVIOUSPAGE");
            string eventValidationServerVariable = GetSeverSideVariableByToken(pageSource, "EVENTVALIDATION");

            //HTML encode
            viewStateServerVariable = HttpUtility.UrlEncode(viewStateServerVariable);
            previousPageServerVariable = HttpUtility.UrlEncode(previousPageServerVariable);
            eventValidationServerVariable = HttpUtility.UrlEncode(eventValidationServerVariable);

            //generate post data
            StringBuilder postDataStringBuilder = new StringBuilder();
            postDataStringBuilder.Append("ctl00_tsm_HiddenField=");
            postDataStringBuilder.Append("&__EVENTTARGET=");
            postDataStringBuilder.Append("&__EVENTARGUMENT=");
            postDataStringBuilder.Append("&__VIEWSTATE=" + viewStateServerVariable);
            postDataStringBuilder.Append("&__PREVIOUSPAGE=" + previousPageServerVariable);
            postDataStringBuilder.Append("&__EVENTVALIDATION=" + eventValidationServerVariable);
            postDataStringBuilder.Append("&ctl00%24Menu1%24s1%24txtSearch=");
            postDataStringBuilder.Append("&ctl00%24cph1%24lg1%24txtEmail=ssattin%40gmail.com");
            postDataStringBuilder.Append("&ctl00%24cph1%24lg1%24txtPassword=dennis10");
            postDataStringBuilder.Append("&ctl00%24cph1%24lg1%24chkRemember=on");
            postDataStringBuilder.Append("&ctl00%24cph1%24lg1%24btnLogin=Login");

            //post the data
            Byte[] postData = Encoding.UTF8.GetBytes(postDataStringBuilder.ToString());
            httpWebRequest = (HttpWebRequest)(WebRequest.Create("http://www.eoddata.com/"));
            httpWebRequest.CookieContainer = cookieContainer;
            httpWebRequest.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, #/#";
            httpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.ContentLength = postData.Length;

            //write the data to the stream
            Stream requestStream = httpWebRequest.GetRequestStream();
            requestStream.Write(postData, 0, postData.Length);
            requestStream.Close();
            webResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            //get the response details
            using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
            {
                //get the page response
                //pageSource = HttpUtility.HtmlEncode(streamReader.ReadToEnd());
                pageSource = (streamReader.ReadToEnd());
            }

            if (string.IsNullOrEmpty(pageSource))
            {
                throw new Exception("Returned null page source from posting login to http://www.eoddata.com/");
            }

            LoggedIn = true;
            CookieContainer = cookieContainer;
        }

        public string DownloadSymbolList(string url)
        {
            if (!LoggedIn)
            {
                throw new Exception("Must be logged in with valid CookieContainer to download a symbol list");
            }

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.CookieContainer = CookieContainer; //use cookie container obtained from logging in.
            httpWebRequest.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, #/#";
            httpWebRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
            httpWebRequest.Method = "GET";
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            var webResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            //2 reference the requested post variables for login e.g. viewstate
            string pageSource = null;

            //get the response details
            using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
            {
                //get the page response
                //pageSource = HttpUtility.HtmlEncode(streamReader.ReadToEnd());
                pageSource = (streamReader.ReadToEnd());
            }

            return pageSource;
        }

        private static string GetSeverSideVariableByToken(string textToSearch, string token)
        {
            string searchStringStart = string.Format("id=\"__{0}\" value=\"",token);
            const string searchStringEnd = "\" />";

            int startIndex = textToSearch.IndexOf(searchStringStart) + searchStringStart.Length;
            int endIndex = textToSearch.Remove(0, startIndex).IndexOf(searchStringEnd);

            return textToSearch.Substring(startIndex, endIndex);
        }
    }
}
